<?php
session_start();

// 检查是否登录，如果需要的话
if (!isset($_SESSION['user_id'])) {
    // 如果用户未登录，可以通过Cookie自动填充用户名（如果存在）
    if (isset($_COOKIE['user_name'])) {
        $username = $_COOKIE['user_name'];
    } else {
        header('Location: login.php');
        exit;
    }
} else {
    // 如果已登录，获取用户名
    $host = 'localhost';
    $db   = 'dev_community';
    $user = 'root'; // 请替换为您的数据库用户名
    $pass = 'root'; // 请替换为您的数据库密码
    $charset = 'utf8mb4';

    $dsn = "mysql:host=$host;dbname=$db;charset=$charset";
    $options = [
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES   => false,
    ];

    try {
        $pdo = new PDO($dsn, $user, $pass, $options);
    } catch (\PDOException $e) {
        throw new \PDOException($e->getMessage(), (int)$e->getCode());
    }

    $stmt = $pdo->prepare("SELECT username FROM users WHERE id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $user = $stmt->fetch();
    $username = $user['username'];
}

// 获取帖子ID，这里假设是通过GET参数传递的
$questionId = isset($_GET['id']) ? intval($_GET['id']) : 0;
if ($questionId == 0) {
    die("帖子ID不存在！");
}

// 获取帖子信息
$stmt = $pdo->prepare("SELECT q.id, q.title, q.content, q.created_at, u.username, q.user_id AS post_user_id, q.view_count FROM questions q INNER JOIN users u ON q.user_id = u.id WHERE q.id = ?");
$stmt->execute([$questionId]);
$question = $stmt->fetch();

// 检查当前用户是否是发帖人
$isPostOwner = $question['post_user_id'] === $_SESSION['user_id'];

// 处理删除请求
if (isset($_POST['delete'])) {
    // 删除帖子及其相关回答
    try {
        // 开始事务
        $pdo->beginTransaction();

        // 删除回答
        $stmt = $pdo->prepare("DELETE FROM answers WHERE question_id = ?");
        $stmt->execute([$questionId]);

        // 删除帖子
        $stmt = $pdo->prepare("DELETE FROM questions WHERE id = ?");
        $stmt->execute([$questionId]);

        // 提交事务
        $pdo->commit();

        // 删除成功后重定向到首页
        header('Location: index.php');
        exit;
    } catch (\PDOException $e) {
        // 回滚事务
        $pdo->rollBack();
        die("删除帖子失败: " . $e->getMessage());
    }
}

// 获取回答信息
$stmt = $pdo->prepare("SELECT a.id, a.content, a.created_at, u.username FROM answers a INNER JOIN users u ON a.user_id = u.id WHERE a.question_id = ?");
$stmt->execute([$questionId]);
$answers = $stmt->fetchAll();

// 更新帖子浏览数
$stmt = $pdo->prepare("UPDATE questions SET view_count = view_count + 1 WHERE id = ?");
$stmt->execute([$questionId]);
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智界论坛 - 查看帖子</title>
    <link rel="stylesheet" type="text/css" href="css/bootstrap.css"/>
    <link rel="stylesheet" type="text/css" href="css/qs.css"/>
</head>

<body>
    <div class="panel">
        <div class="panel-heading">
            <h2>智界论坛</h2>
            <div class="header-actions">
                <div class="button-group">
                    <!-- 去掉注册登录等按钮 -->
                </div>
            </div>
        </div>
        <div class="container">
            <h3><?php echo htmlspecialchars($question['title']); ?></h3>
            <div class="post-details">
                <span>发布者：<?php echo htmlspecialchars($question['username']); ?></span>
                <span>发布时间：<?php echo htmlspecialchars($question['created_at']); ?></span>
                <span>浏览数：<?php echo htmlspecialchars($question['view_count']); ?></span>
            </div>
            <div class="post-content">
                帖子内容：<?php echo nl2br(htmlspecialchars($question['content'])); ?>
            </div>
            <!-- 如果是发帖人，显示删除按钮 -->
            <?php if ($isPostOwner): ?>
                <div class="delete-post">
                    <form method="post" action="" onsubmit="return confirm('确定要删除此帖子吗？');">
                        <input type="hidden" name="delete" value="1">
                        <input type="submit" value="删除帖子" class="btn btn-danger">
                    </form>
                </div>
            <?php endif; ?>
        </div>
        <div class="answer-container">
            <?php foreach ($answers as $answer): ?>
                <div class="answer-item">
                    <h4>回答</h4>
                    <div class="answer-details">
                        <span class="answer-author">回答者：<?php echo htmlspecialchars($answer['username']); ?></span>
                        <span class="answer-date">回答时间：<?php echo htmlspecialchars($answer['created_at']); ?></span>
                    </div>
                    <div class="answer-content">
                        <p><?php echo nl2br(htmlspecialchars($answer['content'])); ?></p>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
        <div class="reply-form">
            <h5>我来回答</h5>
            <form method="post" action="reply.php" enctype="multipart/form-data">
                <input type="hidden" name="question_id" value="<?php echo $questionId; ?>">
                <p><textarea name="content" rows="10" required></textarea></p>
                <p><input type="submit" value="提交" name="submit" class="btn"></p>
            </form>
        </div>
        <div class="return-home">
            <a href="index.php" class="btn">返回主页</a>
        </div>
    </div>

    <!-- 添加网页尾部 -->
    <div class="footer">
        <p>&copy; 智界论坛·保留所有权利</p>
        <p>版权所有☆Qualan<sup>&copy;</sup> Q_L</p>
    </div>
</body>

</html>